<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/12/4
 * Time: 11:01
 */
namespace backend\models;

use backend\controllers\InstationMessageController;
use common\models\ApplicationResult;
use common\models\Package;
use common\models\PackageApplication;
use common\models\PackageInitiation;
use common\models\PackageInitiationIncome;
use common\models\PackageTransferHistory;
use common\models\Project;
use common\models\Responses;

class Packageapply extends \yii\db\ActiveRecord
{

    //获取资产包基础信息
    public static function getPackageData($packageID){
        if (!empty($packageID)){
            $packageData = (new \yii\db\Query())->from(Package::tableName())->where(['=','id',$packageID])->one();
            if (!empty($packageData)){
                return Responses::response200($packageData);
            }

            return Responses::response400('无数据');
        }
    }

    //-------------------流转 前期处理及维护-----------------
    public static function getPackageTransferHistory($packageID){
        if (!empty($packageID)){
            $packageTransData = (new \yii\db\Query())->from(PackageTransferHistory::tableName())->where(['in','package_id',$packageID])->all();
            if (!empty($packageTransData)){
                return Responses::response200($packageTransData);
            }

            return Responses::response400('无数据');
        }
    }
    //-------------------卖家提供的信息资料---资产成交的期限和成交方式--------------
    //-------------------当地共同处置资产包的合作伙伴情况-----------------
    //-------------------当地司法环境对所立项目的法律支持分析-----------------
    //-------------------卖家报价、及未来价格可谈判空间-----------------
    //-------------------团队组成-----------------
    public static function getPackageInitiation($packageID){
        if (!empty($packageID)){
            $packageInitiationData = (new \yii\db\Query())->from(PackageInitiation::tableName())->where(['in','package_id',$packageID])->all();
            if (!empty($packageInitiationData)){
                return Responses::response200($packageInitiationData);
            }
            return Responses::response400('无数据');
        }
    }

    //-------------------工作计划-----------------
    public static function getPackagePlan($packageID){
        if (!empty($packageID)){
            $packageInitiationPlanData = (new \yii\db\Query())->from(PackageInitiationPlan::tableName())->where(['in','package_id',$packageID])->all();
            if (!empty($packageInitiationPlanData)){
                return Responses::response200($packageInitiationPlanData);
            }

            return Responses::response400('无数据');
        }
    }
    //-------------------团队收益分配-----------------
    public static function getPackageInitiationIncome($packageID){
        if (!empty($packageID)){
            $packageInitiationIncomeData = (new \yii\db\Query())->from(PackageInitiationIncome::tableName())->where(['in','package_id',$packageID])->all();
            if (!empty($packageInitiationIncomeData)){
                return Responses::response200($packageInitiationIncomeData);
            }

            return Responses::response400('无数据');
        }
    }

    //保存立项申请 并发送立项审核消息给管理员
    public static function updatePackageInitiationReason($packageID,$reasonText,$state){
        $transaction  = \Yii::$app->db->beginTransaction();
        try{
            //保存package_application
            $modelclass = PackageInitiation::findOne(['package_id'=>$packageID]);
            $packageModleClass = Package::findOne($packageID);
            $modelclass->reason = $reasonText;
            $packageModleClass->state = \Yii::$app->params['LIXIANGSHENPIN'];
            $packageState = $packageModleClass->save(false);
            $projectState = Project::updateAll(['status'=>3],['package_id'=>$packageID]);
            $packageApplicationId = 0; // package_application 表id
            //保存申请立项信息
            if (!empty($packageID)){
                $packageApplicationModel =  PackageApplication::find()->where(['package_id'=>$packageID,'type'=>1])->andWhere(['=','workflow_status',1])->one();
                $packageApplicationId = (new \yii\db\Query())->select('id')->from('package_application')->where(['=','package_id',$packageID])->andWhere(['=','workflow_status',1])->one()['id'];
            }else{
                $packageApplicationModel = new PackageApplication();
            }

            if (empty($packageApplicationModel)){
                $packageApplicationModel = new PackageApplication();
            }
            $packageApplicationModel->package_id = $packageID;
            $packageApplicationModel->workflow_status = 1;
            $packageApplicationModel->is_package = 1;
            $packageApplicationModel->type = \Yii::$app->params['LIXIANG'];  //
            $packageApplicationModel->proposer = \Yii::$app->user->getId();
            $packageApplicationModel->reason = $reasonText;
            $packageApplicationState = $packageApplicationModel->save(false);
            if (empty($packageApplicationId)){
                $packageApplicationId = $packageApplicationModel->attributes['id'];
            }
            //保存立项 关联表 application_result
            if (!empty($packageApplicationId)){
                $applicationResultModel =  ApplicationResult::findOne(['application_id'=>$packageApplicationId]);
            }else{
                $applicationResultModel = new ApplicationResult();
            }
            if (empty($applicationResultModel)){
                $applicationResultModel = new ApplicationResult();
            }

            $applicationResultModel->application_id = $packageApplicationId;
            $applicationResultModel->user_id = 0; //默认审核立项管理员为空
            $applicationResultState = $applicationResultModel->save(false);
            if($modelclass->save() && $packageState && $packageApplicationState && $applicationResultState){
                $transaction->commit();
//                InstationmessageController::actionIndex();
                return Responses::response200();
            }
        }catch (\Exception $exception){
            $transaction->rollBack();
            return Responses::response400('发起协同失败');
        }
    }

    //获取预评估表完成情况
    public static function desireProject($packageID){
        if (!empty($packageID)){
            $countDiya = (new \yii\db\Query())->select('count(*) as count')->from(Project::tableName())->andWhere(['=','package_id',$packageID])->andWhere(['=','type',2])->andWhere(['=','is_highlights',1])->count('*');
            $countHunhe = (new \yii\db\Query())->select('count(*) as count')->from(Project::tableName())->andWhere(['!=','type',2])->andWhere(['=','package_id',$packageID])->andWhere(['=','is_highlights',1])->count('*');
            $count = [
                'Diya'=>$countDiya,
                'Hunhe'=>$countHunhe
            ];
            if (!empty($count)){
                return Responses::response200($count);
            }
            return Responses::response400('无数据');
        }
    }

    /*
     * 保存访问审批
     */
    public static function saveFWApply($data){
        $package_id = $data['package_id'];
        $is_package = $data['is_package'];
        $reason = $data['reason'];
        $proposer = $data['proposer'];
        $user_id = $data['user_id'];
        $transaction  = \Yii::$app->db->beginTransaction();
        try {
            $accessApplicationId = 0;
            $accessApplicationModel = new PackageApplication;
            $accessApplicationModel->package_id = $package_id;
            $accessApplicationModel->is_package = $is_package;
            $accessApplicationModel->type = \Yii::$app->params['FANGWEN'];
            $accessApplicationModel->reason = $reason;
            $accessApplicationModel->proposer = $proposer;
            $accessApplicationState = $accessApplicationModel->save(false);
            if (empty($accessApplicationId)) {
                $accessApplicationId = $accessApplicationModel->attributes['id'];
            }

            $applicationResultModel = new ApplicationResult();
            $applicationResultModel->application_id = $accessApplicationId;
            $applicationResultModel->user_id = $user_id[0];
            $applicationResultState = $applicationResultModel->save(false);
            if ($accessApplicationState && $applicationResultState) {

                //TODO 资产包申请访问日志
                $res = (new PackageApplication())->addPackageLog($accessApplicationModel->id, $package_id,$proposer, \Yii::$app->params['FANGWEN']);
                if (!$res['state']) {
                    throw new \Exception($res['msg']);
                }

                $transaction->commit();
                return json_encode(Responses::response200());
            }
            $transaction->rollBack();
            return json_encode(Responses::response400('发起申请查看失败'));
        }catch (\Exception $exception){
            $transaction->rollBack();
            return json_encode(Responses::response400('发起申请查看失败'));
        }
    }
}
